const pageHelper = require('../config/path_resolver').getRootConfigPath('path_resolver.js').getRootConfigPath('path_resolver.js').getRootConfigPath('project_helpers_config.js').(_, __, helper) => helper.replace('.js', '');
const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { teamStore } = require('../config/path_resolver').getRootConfigPath('path_resolver.js').getRootConfigPath('path_resolver.js').getProjectStorePath('modules/team_store.js');
const Day = require('dayjs');
const { logEvent } = require('../../../../helpers/log_helper.js');
const { getNetworkStatus, listenNetworkStatus } = require('../../../../helpers/network_helper.js');

Page({
  data: {
    projectId: '',
    workloadData: [], // 格式：[{memberId, memberName, workload, role}]
    totalWorkload: 100, // 总工作量百分比
    originalWorkload: [], // 保存初始工作量数据以检测变更
    hasChanged: false,
    submitting: false,
    showMemberRank: true, // 是否显示成员排名
    error: '' // 错误信息
  },
  
  onLoad: async function(options) {
    // 网络检测
    const net = await getNetworkStatus();
    if (!net.isConnected) {
      wx.showToast({ title: '当前无网络，请检查连接', icon: 'none' });
    } else if (net.networkType === '2g') {
      wx.showToast({ title: '当前为2G弱网，体验可能受影响', icon: 'none' });
    }
    listenNetworkStatus((res) => {
      if (!res.isConnected) wx.showToast({ title: '网络已断开', icon: 'none' });
      else if (res.networkType === '2g') wx.showToast({ title: '当前为2G弱网', icon: 'none' });
    });
    logEvent('page_load', { page: 'plm_team_workload' });
    
    // 创建MobX绑定
    this.storeBindings = createStoreBindings(this, {
      store: teamStore,
      fields: ['loading', 'error', 'teamMembers'],
      actions: ['getProjectTeam', 'updateTeamWorkload']
    });
    
    if (options.projectId) {
      this.setData({ projectId: options.projectId });
      
      // 加载团队成员列表
      this.loadTeamMembers(options.projectId);
    } else {
      pageHelper.showErrorToast('缺少项目ID');
      setTimeout(() => wx.navigateBack(), 1500);
    }
  },
  
  // 加载团队成员
  loadTeamMembers: function(projectId) {
    this.getProjectTeam(projectId).then(() => {
      if (this.data.teamMembers && this.data.teamMembers.length > 0) {
        this._initWorkloadData();
      } else {
        this.setData({
          error: '未找到团队成员'
        });
      }
    }).catch(err => {
      this.setData({
        error: '加载团队成员失败：' + err.message
      });
    });
  },
  
  // 初始化工作量数据
  _initWorkloadData: function() {
    // 转换团队成员数据为工作量数据
    const workloadData = this.data.teamMembers.map(member => ({
      memberId: member._id,
      memberName: member.userName,
      role: member.role,
      roleText: member.getRoleDisplay(),
      joinTime: Day(member.joinTime).format('YYYY-MM-DD'),
      workload: member.workload || 0
    }));
    
    // 按工作量倒序排序
    workloadData.sort((a, b) => b.workload - a.workload);
    
    // 保存原始数据以检测变更
    const originalWorkload = JSON.stringify(workloadData.map(item => ({
      memberId: item.memberId,
      workload: item.workload
    })));
    
    this.setData({
      workloadData,
      originalWorkload
    });
    
    // 计算当前总工作量
    this._calculateTotalWorkload();
  },
  
  // 切换成员排名显示
  toggleMemberRank: function() {
    this.setData({
      showMemberRank: !this.data.showMemberRank
    });
  },
  
  // 修改成员工作量
  onWorkloadChange: function(e) {
    const index = e.currentTarget.dataset.index;
    const value = parseFloat(e.detail.value) || 0;
    
    // 更新工作量数据
    const workloadData = this.data.workloadData;
    workloadData[index].workload = value;
    
    this.setData({ workloadData });
    
    // 计算总工作量并检查是否有变更
    this._calculateTotalWorkload();
    this._checkChanges();
  },
  
  // 计算总工作量
  _calculateTotalWorkload: function() {
    const totalWorkload = this.data.workloadData.reduce((sum, item) => {
      return sum + (parseFloat(item.workload) || 0);
    }, 0);
    
    this.setData({ totalWorkload });
    
    // 如果总和不是100%，显示错误
    if (Math.abs(totalWorkload - 100) > 0.1) {
      this.setData({
        error: `工作量总和必须为100%，当前为${totalWorkload.toFixed(1)}%`
      });
    } else {
      this.setData({ error: '' });
    }
  },
  
  // 检查是否有变更
  _checkChanges: function() {
    const currentWorkload = JSON.stringify(this.data.workloadData.map(item => ({
      memberId: item.memberId,
      workload: item.workload
    })));
    
    this.setData({
      hasChanged: currentWorkload !== this.data.originalWorkload
    });
  },
  
  // 平均分配工作量
  distributeEvenly: function() {
    const memberCount = this.data.workloadData.length;
    if (memberCount === 0) return;
    
    // 计算每人平均工作量（保留一位小数）
    const averageWorkload = parseFloat((100 / memberCount).toFixed(1));
    
    // 更新所有成员工作量
    const workloadData = this.data.workloadData.map(item => ({
      ...item,
      workload: averageWorkload
    }));
    
    this.setData({ workloadData });
    
    // 计算总工作量并检查是否有变更
    this._calculateTotalWorkload();
    this._checkChanges();
  },
  
  // 按角色分配工作量
  distributeByRole: function() {
    const workloadData = this.data.workloadData;
    if (workloadData.length === 0) return;
    
    // 计算各角色人数
    const roleCounts = {
      leader: 0,
      manager: 0,
      member: 0
    };
    
    workloadData.forEach(item => {
      if (roleCounts[item.role] !== undefined) {
        roleCounts[item.role]++;
      }
    });
    
    // 设置各角色的工作量百分比
    const roleWorkloads = {
      leader: 40, // 项目负责人占40%
      manager: 30, // 项目经理占30%
      member: 30  // 普通成员平分剩余30%
    };
    
    // 按角色分配工作量
    const newWorkloadData = workloadData.map(item => {
      let workload = 0;
      
      if (item.role === 'leader') {
        // 项目负责人均分40%
        workload = roleWorkloads.leader / Math.max(1, roleCounts.leader);
      } else if (item.role === 'manager') {
        // 项目经理均分30%
        workload = roleWorkloads.manager / Math.max(1, roleCounts.manager);
      } else {
        // 团队成员均分30%
        workload = roleWorkloads.member / Math.max(1, roleCounts.member);
      }
      
      return {
        ...item,
        workload: parseFloat(workload.toFixed(1))
      };
    });
    
    this.setData({ workloadData: newWorkloadData });
    
    // 计算总工作量并检查是否有变更
    this._calculateTotalWorkload();
    this._checkChanges();
  },
  
  // 保存工作量分配
  saveWorkload: function() {
    if (this.data.submitting) return;
    
    // 验证总工作量是否为100%
    if (Math.abs(this.data.totalWorkload - 100) > 0.1) {
      pageHelper.showErrorToast('工作量总和必须为100%');
      return;
    }
    
    this.setData({ submitting: true });
    
    // 格式化提交数据
    const workloadData = this.data.workloadData.map(item => ({
      memberId: item.memberId,
      workload: parseFloat(item.workload)
    }));
    
    // 调用Store方法保存工作量分配
    this.updateTeamWorkload(this.data.projectId, workloadData)
      .then(() => {
        pageHelper.showSuccessToast('工作量分配已保存');
        
        // 更新原始数据
        this.setData({
          originalWorkload: JSON.stringify(workloadData),
          hasChanged: false,
          submitting: false
        });
        
        // 返回上一页
        setTimeout(() => wx.navigateBack(), 1500);
      })
      .catch(err => {
        pageHelper.showErrorToast('保存失败：' + err.message);
        this.setData({ submitting: false });
      });
  },
  
  // 重置工作量分配
  resetWorkload: function() {
    // 重新加载团队成员
    this.loadTeamMembers(this.data.projectId);
  },
  
  onUnload: function() {
    // 销毁MobX绑定
    this.storeBindings.destroyStoreBindings();
  }
}); 